<?php

namespace lxs\aliyun;

use Alipay\OpenAPISDK\Util\AlipayLogger;
use Alipay\OpenAPISDK\Api\AlipayOpenAppQrcodeApi;
use Alipay\OpenAPISDK\Util\AlipayConfigUtil;
use Alipay\OpenAPISDK\Util\Model\AlipayConfig;
use GuzzleHttp\Client;
use Alipay\OpenAPISDK\ApiException;
use Alipay\OpenAPISDK\Model\AlipayOpenAppQrcodeCreateModel;


use Illuminate\Support\Facades\Log;

class AliyunQrcode
{

    private $alipayconfigutil = null;

    public function __construct($appid, $secret, $publicKey)
    {
        if (!$publicKey) {
            log::write('error', '支付宝创建小程序二维码失败: 支付宝公钥不正确或空');
        }
        AlipayLogger::setNeedEnableLogger( needEnableLogger: false);
        $alipayConfig = new AlipayConfig();
        $alipayConfig->setAppId($appid);
        $alipayConfig->setPrivateKey($secret);
        $alipayConfig->setAlipayPublicKey($publicKey);
        $this->alipayconfigutil = new AlipayConfigUtil($alipayConfig);
    }

    public function getMiniCode(string $path, string $param)
    {

        $apiInstance = new AlipayopenAppQrcodeApi(
            new Client()
        );
        $apiInstance->setAlipayConfigUtil($this->alipayconfigutil);
        $data = new AlipayOpenAppQrcodeCreateModel();
        $data->setUrlParam($path);
        $data->setQueryParam($param);
        $data->setDescribe("邀请查询");

        try {
            $result = $apiInstance->create($data);
            if (isset($result['qrCodeUrlCircleBlue'])) {
                return $result['qrCodeUrlCircleBlue'];
            } else {
                return false;
            }
        } catch (ApiException $e) {
            log::write('error', '支付宝创建小程序二维码失败: ' . $e->getMessage());
            return false;
        }
    }
}
